﻿using System;
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.Store;

namespace Dexter.Search.Lucene.Wrapper {
	public class IndexService : IDisposable {
		readonly Analyzer analyzer;
		readonly Directory indexDirectory;
		bool isDisposed;
		IndexWriter luceneWriter;

		public IndexService ( Directory indexDirectory , Analyzer analyzer ) {
			this.indexDirectory = indexDirectory;
			this.analyzer = analyzer;
		}

		#region IDisposable Members

		public void Dispose ( ) {
			if ( !this.isDisposed && ( this.luceneWriter != null ) ) {
				this.luceneWriter.Optimize ( );
				this.luceneWriter.Commit ( );
				this.luceneWriter.Close ( );
				this.isDisposed = true;
			}
			this.luceneWriter = null;
		}

		#endregion

		public IndexWriter GetWriter ( ) {
			if ( this.isDisposed ) {
				this.isDisposed = false;
			}
			return this.luceneWriter ?? ( this.luceneWriter = new IndexWriter ( indexDirectory , analyzer , IndexWriter.MaxFieldLength.UNLIMITED ) );
		}
	}
}